import { API_HOST, API_VERSION, URL_GET_TOKEN } from "./config";

let isLogining = false;
let retrySuccess = false;
let eventList = []
function wxLogin() {
  return new Promise((resolve, reject) => {
    if (retrySuccess) {
      resolve()
      return;
    } else {
      eventList.push(resolve);
      if (isLogining) {
        return
      } else {
        isLogining = true;
      }
    }
    wx.login({
      success: function (res) {
        if (res.code) {
          // console.log('wx.login', res)
          getToken(res.code, resolve, reject)
        } else {
          reject()
        }
      },
      fail: function () {
        reject()
      }
    })
  })
}
function getToken(code, resolve, reject) {
  // let version = API_VERSION;
  wx.request({
    url: `${API_HOST}${URL_GET_TOKEN}`,
    data: {
      code: code
    },
    method: 'POST',
    success: function (res) {
      const { statusCode, data: respData } = res;
      if (statusCode == 200 && respData.status === 200) {
        wx.setStorageSync("token", `Bearer ${respData.data.token}`)
        wx.setStorageSync("code", code)
        wx.setStorageSync("openid", respData.data.openid)
        isLogining = false
        retrySuccess = true
        eventList.forEach(item => {
          item()
        })
        eventList = []
      } else {
        isLogining = false;
        retrySuccess = false;
        reject()
      }

    },
    fail: function (res) {
      isLogining = false;
      retrySuccess = false;
      reject()
    },
  })
}

module.exports = {
  wxLogin
}
